import React, { useState, useEffect } from 'react'
import Header from './components/Header'
import InputSection from './components/InputSection'
import OutputSection from './components/OutputSection'
import InkAnimation from './components/InkAnimation'
import HistoryPanel from './components/HistoryPanel'
import DynamicBackground from './components/DynamicBackground'
import PerformanceMonitor from './components/PerformanceMonitor'

import { generatePoetryResponse } from './services/fastgpt'
import { generatePoemImage } from './services/imageGeneration'
import { saveHistory, getHistory, STORAGE_KEYS } from './utils/storage'
import { createPlaceholderImageUrl } from './services/imageGeneration'
import { triggerShareCardPregeneration } from './services/sharePregeneration'

function App() {
  const [userInput, setUserInput] = useState('')
  const [aiResponse, setAiResponse] = useState(null)
  const [isLoading, setIsLoading] = useState(false)
  const [isGeneratingImage, setIsGeneratingImage] = useState(false)
  const [generatedImage, setGeneratedImage] = useState(null)
  const [history, setHistory] = useState([])
  const [hideMainContent, setHideMainContent] = useState(false) // 控制main元素显示/隐藏
  const [currentPreviewRecordId, setCurrentPreviewRecordId] = useState(null)
  const [recordIdBeforePreview, setRecordIdBeforePreview] = useState(null); // 新增状态：保存进入预览前的记录ID
  const [showPerformanceMonitor, setShowPerformanceMonitor] = useState(false) // 性能监控面板显示状态

  // 格式化诗句为四行显示
  const formatPoemLines = (poem) => {
    if (!poem) return []

    // 先按换行符分割
    let lines = poem.split('\n').filter(line => line.trim())

    // 如果只有1-2行，可能是用逗号或句号分隔的
    if (lines.length <= 2) {
      // 尝试按标点符号分割
      const fullText = lines.join('')
      const segments = fullText.split(/([，。！？；：])/g)

      const newLines = []
      let currentLine = ''

      for (let i = 0; i < segments.length; i++) {
        const segment = segments[i].trim()
        if (!segment) continue

        if (/[，。！？；：]/.test(segment)) {
          // 是标点符号，加到当前行
          currentLine += segment
          newLines.push(currentLine)
          currentLine = ''
        } else {
          // 是文字内容
          currentLine += segment
        }
      }

      // 如果还有剩余内容
      if (currentLine.trim()) {
        newLines.push(currentLine.trim())
      }

      lines = newLines.filter(line => line.trim())
    }

    // 确保最多4行，如果超过4行则合并
    if (lines.length > 4) {
      const result = []
      for (let i = 0; i < 4; i++) {
        if (i < 3) {
          result.push(lines[i])
        } else {
          // 最后一行合并剩余内容
          result.push(lines.slice(i).join(''))
          break
        }
      }
      lines = result
    }

    return lines
  }

  // 加载历史记录
  useEffect(() => {
    const savedHistory = getHistory()
    setHistory(savedHistory)
    // 应用启动时，设置currentPreviewRecordId为最新的历史记录ID（如果有）
    if (savedHistory.length > 0) {
      setCurrentPreviewRecordId(savedHistory[0].id)
    }
  }, [])

  const handleSubmit = async (input) => {
    setIsLoading(true)
    setUserInput(input)
    setGeneratedImage(null) // 重置图片状态

    try {
      // 第一步：调用FastGPT API生成诗句和情绪分析
      const response = await generatePoetryResponse(input)
      setAiResponse(response)

      // 第二步：根据诗句生成配图
      setIsGeneratingImage(true)
      let finalImageResult = null
      try {
        const imageResult = await generatePoemImage(response.poem, response.emotion, input)
        setGeneratedImage(imageResult)
        finalImageResult = imageResult

        // 图片生成成功后，立即触发分享卡片预生成
        if (imageResult.success) {
          console.log('🎨 触发分享卡片预生成...')
          triggerShareCardPregeneration({
            poem: response.poem,
            emotion: response.emotion,
            userInput: input,
            generatedImage: imageResult
          })
        }
      } catch (imageError) {
        console.error('图片生成失败:', imageError)

        // 根据错误类型提供更具体的错误信息
        let errorMessage = '图片生成失败，但诗句已完成'
        if (imageError.message.includes('404')) {
          errorMessage = '图片生成任务已过期，请重新尝试'
        } else if (imageError.message.includes('Failed to fetch')) {
          errorMessage = '网络连接问题，请检查网络后重试'
        } else if (imageError.message.includes('CORS') || imageError.message.includes('代理')) {
          errorMessage = '图片服务暂时不可用，请稍后重试'
        }

        const errorImageResult = {
          success: false,
          error: errorMessage,
          canRetry: true, // 标记可以重试
          imageUrl: createPlaceholderImageUrl(taskId), // <--- 新增：即使失败也提供一个占位符图片URL
          originalSample: null // 失败时没有原始sample
        }
        setGeneratedImage(errorImageResult)
        finalImageResult = errorImageResult
      } finally {
        setIsGeneratingImage(false)
      }

      // 保存到历史记录（包含图片信息）
      const record = {
        userInput: input,
        aiResponse: response,
        generatedImage: {
          ...finalImageResult,
          imageUrl: finalImageResult?.imageUrl || finalImageResult?.sample // 保证 imageUrl 字段存在
        }
      }
      saveHistory(record)

      // 更新本地历史状态
      const updatedHistory = getHistory()
      setHistory(updatedHistory)

      // 设置currentPreviewRecordId为最新的记录ID
      if (updatedHistory.length > 0) {
        setCurrentPreviewRecordId(updatedHistory[0].id)
      }

    } catch (error) {
      console.error('API调用失败:', error)
      const errorResponse = {
        poem: "网络不通情意断，\n稍后再试诉心声。\n莫道无缘会佳句，\n片刻之后再相逢。",
        emotion: "略有遗憾",
        analysis: "暂时无法连接到AI服务，请稍后再试。系统将为您保留输入内容。"
      }
      setAiResponse(errorResponse)

      // 即使出错也保存记录
      saveHistory({
        userInput: input,
        aiResponse: errorResponse,
        isError: true
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handleSelectHistory = (record) => {
    console.log('📋 选择历史记录:', record.id, '图片状态:', {
      hasImage: !!record.generatedImage?.imageUrl,
      success: record.generatedImage?.success
    })

    // 确保不在预览模式下 (隐藏主内容)
    setHideMainContent(false)

    // 设置currentPreviewRecordId为选中的历史记录ID
    setCurrentPreviewRecordId(record.id)

    // 立即更新所有状态，确保图片能正确显示
    setUserInput(record.userInput)
    setAiResponse(record.aiResponse)
    setGeneratedImage(record.generatedImage || null) // Update generatedImage for OutputSection
    
    // 为历史记录也触发分享卡片预生成（如果图片存在且成功）
    if (record.generatedImage?.success && record.aiResponse?.poem) {
      console.log('📱 为历史记录触发分享卡片预生成...')
      triggerShareCardPregeneration({
        poem: record.aiResponse.poem,
        emotion: record.aiResponse.emotion,
        userInput: record.userInput,
        generatedImage: record.generatedImage
      })
    }
    
    console.log('✅ 历史记录状态已更新')
  }

  const handleHistoryUpdate = (newHistory) => {
    setHistory(newHistory)
  }

  // 打开背景预览
  const handleOpenBackgroundPreview = (recordId) => {
    console.log('🔍 打开背景预览:', recordId)

    // 存储当前的 recordId，以便退出预览时恢复
    setRecordIdBeforePreview(currentPreviewRecordId);

    // 找到对应的记录并设置状态
    const record = history.find(r => r.id === recordId)
    if (record) {
      console.log('📋 找到预览记录:', record.id, '图片状态:', {
        hasImage: !!record.generatedImage?.imageUrl,
        success: record.generatedImage?.success,
        imageUrl: record.generatedImage?.imageUrl?.substring(0, 100) + '...'
      })

      // 进入预览模式（隐藏主内容）
      setHideMainContent(true)
      // 设置currentPreviewRecordId为选中的记录ID
      setCurrentPreviewRecordId(recordId)

      // 同时更新 aiResponse 和 userInput，确保诗句和输入内容同步
      setAiResponse(record.aiResponse);
      setUserInput(record.userInput);
      // 更新OutputSection的generatedImage，以便在预览模式下内容区域显示正确
      setGeneratedImage(record.generatedImage || null);
    }
  }

  // 预览记录切换（通过DynamicBackground内部控件触发）
  const handlePreviewRecordChange = (record) => {
    console.log('🔄 预览记录切换:', record.id)
    setCurrentPreviewRecordId(record.id)
    // 同时更新 aiResponse 和 userInput，确保诗句和输入内容同步
    setAiResponse(record.aiResponse);
    setUserInput(record.userInput);
    // 更新OutputSection的generatedImage，以便在预览模式下内容区域显示正确
    setGeneratedImage(record.generatedImage || null);
  }

  // 关闭背景预览
  const handleClosePreview = () => {
    console.log('↩️ 关闭背景预览')
    setHideMainContent(false) // 隐藏全屏叠加层

    // 恢复到进入预览前的 recordId
    if (recordIdBeforePreview) {
      const recordToRestore = history.find(r => r.id === recordIdBeforePreview);
      if (recordToRestore) {
        setCurrentPreviewRecordId(recordToRestore.id);
        setAiResponse(recordToRestore.aiResponse);
        setUserInput(recordToRestore.userInput);
        setGeneratedImage(recordToRestore.generatedImage || null);
      } else {
        // 如果保存的 recordId 在历史记录中找不到了（比如被删除了），则回退到最新的有效记录
        const latestRecordWithImage = history.find(record => record.generatedImage?.imageUrl);
        if (latestRecordWithImage) {
          setCurrentPreviewRecordId(latestRecordWithImage.id);
          setAiResponse(latestRecordWithImage.aiResponse);
          setUserInput(latestRecordWithImage.userInput);
          setGeneratedImage(latestRecordWithImage.generatedImage || null);
        } else {
          // 彻底清空所有状态
          setCurrentPreviewRecordId(null);
          setAiResponse(null);
          setUserInput('');
          setGeneratedImage(null);
        }
      }
    } else {
      // 如果 recordIdBeforePreview 为空（例如直接从无历史记录状态进入预览），则回退到最新的有效记录
      const latestRecordWithImage = history.find(record => record.generatedImage?.imageUrl);
      if (latestRecordWithImage) {
        setCurrentPreviewRecordId(latestRecordWithImage.id);
        setAiResponse(latestRecordWithImage.aiResponse);
        setUserInput(latestRecordWithImage.userInput);
        setGeneratedImage(latestRecordWithImage.generatedImage || null);
      } else {
        // 彻底清空所有状态
        setCurrentPreviewRecordId(null);
        setAiResponse(null);
        setUserInput('');
        setGeneratedImage(null);
      }
    }
    setRecordIdBeforePreview(null); // 清空保存的 ID
  }

  // 重新生成图片
  const handleRegenerateImage = async () => {
    if (!aiResponse?.poem) {
      console.warn('没有诗句，无法重新生成图片')
      return
    }

    console.log('🔄 开始重新生成图片...')
    setIsGeneratingImage(true)

    // 显示重新生成的状态，但保留之前的图片直到新图片生成完成
    setGeneratedImage(prev => ({
      ...prev,
      regenerating: true
    }))

    try {
      const imageResult = await generatePoemImage(
        aiResponse.poem,
        aiResponse.emotion || '诗意盎然',
        userInput
      )

      console.log('🔄 重新生成图片结果:', imageResult)
      setGeneratedImage(imageResult) // 更新 OutputSection 的 generatedImage

      let recordIndexToUpdate = -1; // 默认没有找到可更新的记录

      // 1. 优先尝试更新 `currentPreviewRecordId` 对应的记录
      if (currentPreviewRecordId) {
        recordIndexToUpdate = history.findIndex(record => record.id === currentPreviewRecordId);
      }

      // 2. 如果 `currentPreviewRecordId` 无效或找不到，且历史记录不为空，则尝试更新最新的记录 (history[0])
      if (recordIndexToUpdate === -1 && history.length > 0) {
        recordIndexToUpdate = 0; // 假设最新记录是目标
      }

      const updatedHistory = [...history]; // 创建历史记录的副本

      if (recordIndexToUpdate !== -1) {
        // 找到了可更新的记录，执行更新
        updatedHistory[recordIndexToUpdate] = {
          ...updatedHistory[recordIndexToUpdate],
          generatedImage: {
            ...imageResult,
            imageUrl: imageResult?.imageUrl || imageResult?.sample // 保证 imageUrl
          }
        };
        setHistory(updatedHistory); // 更新 history 状态
        localStorage.setItem(STORAGE_KEYS.HISTORY, JSON.stringify(updatedHistory)); // 持久化更新后的 history

        // 确保背景图反映最新重新生成的图片
        setCurrentPreviewRecordId(updatedHistory[recordIndexToUpdate].id); // 保持 currentPreviewRecordId 指向更新后的记录
        console.log('✅ 历史记录中的图片已成功更新。');

      } else {
        // 如果没有找到可更新的历史记录（即 history 为空，或者 currentPreviewRecordId 和 history[0] 都无效/不存在）
        // 重新生成操作不应创建新记录。这里只更新当前显示的图片，不影响历史记录。
        console.warn('⚠️ 重新生成操作未能找到匹配的历史记录进行更新。将不会修改历史记录，只更新当前显示图片。');
        // 不需要在这里创建新记录，因为"重新生成"的目的是修改已存在的记录。
      }

    } catch (error) {
      console.error('🔄 重新生成图片失败:', error)
      const errorImageResult = {
        success: false,
        error: '重新生成图片失败：' + error.message,
        canRetry: true
      }
      setGeneratedImage(errorImageResult)
    } finally {
      setIsGeneratingImage(false)
    }
  }

  const handleRestart = () => {
    // 重置所有状态
    setUserInput('')
    setAiResponse(null)
    setIsLoading(false)
    setIsGeneratingImage(false)
    setGeneratedImage(null)
    setHideMainContent(false)
    // 注意：不清除历史记录，保持持久化
  }

  return (
    <div className="min-h-screen relative overflow-hidden">
      {/* 动态背景（包含情绪色彩和生成的图片） */}
      <DynamicBackground
        generatedImage={generatedImage}
        emotion={aiResponse?.emotion}
        isVisible={hideMainContent}
        hideMainContent={hideMainContent}
        history={history}
        currentRecordId={currentPreviewRecordId}
        onRecordChange={handlePreviewRecordChange}
        onClosePreview={handleClosePreview}
      />

      {/* 背景水墨动画 */}
      <InkAnimation emotion={aiResponse?.emotion} />

      {/* Header */}
      <div className={`relative z-10 transition-all duration-500 ${hideMainContent ? 'opacity-0 pointer-events-none' : 'opacity-100'}`}>
        <Header />
      </div>

      {/* 主要内容 */}
      <div className={`relative z-10 transition-all duration-500 ${hideMainContent ? 'opacity-0 pointer-events-none' : 'opacity-100'}`}>
        <main className="container mx-auto px-4 py-8 max-w-4xl">
          <div className="space-y-8">
            {/* 输入区域 */}
            <InputSection
              onSubmit={handleSubmit}
              isLoading={isLoading}
            />

            {/* 输出区域 - 预览模式下不显示 */}
            {(aiResponse || isLoading) && !hideMainContent && (
              <OutputSection
                response={aiResponse}
                isLoading={isLoading}
                userInput={userInput}
                generatedImage={generatedImage}
                isGeneratingImage={isGeneratingImage}
                onToggleMainContent={setHideMainContent}
                onRestart={handleRestart}
                onImageGenerated={setGeneratedImage}
                onRegenerateImage={handleRegenerateImage}
              />
            )}
          </div>
        </main>
      </div>

      {/* 当隐藏主内容时显示的诗句叠加层 */}
      {hideMainContent && aiResponse && (
        <div className="fixed inset-0 z-40 flex flex-col items-center justify-center pointer-events-none p-6 select-none">
          <div className="max-w-5xl mx-auto text-center">
            {/* 诗句内容 */}
            <div className="mb-16">
              <div className="text-3xl md:text-4xl lg:text-5xl xl:text-6xl poem-overlay animate-poem-fade-in select-none"
                   style={{ lineHeight: '1.8', userSelect: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none' }}>
                {formatPoemLines(aiResponse.poem).map((line, index) => (
                  <div key={index} className="mb-4 select-none">
                    {line}
                  </div>
                ))}
              </div>
            </div>

            {/* 情绪标签 */}
            <div className="inline-flex items-center">
              {/* <span className="text-white text-lg opacity-90 font-chinese">情绪解读</span>
              <div className="w-px h-6 bg-white opacity-30"></div>
              <span className="text-white text-lg opacity-90 font-chinese">
                {aiResponse.emotion}
              </span> */}
            </div>

            {/* 用户输入 */}
            {userInput && (
              <div className="text-white text-lg md:text-xl opacity-85 poem-overlay select-none"
                   style={{
                     animation: 'poemFadeIn 1s ease-out 1.2s forwards',
                     opacity: 0,
                     userSelect: 'none',
                     WebkitUserSelect: 'none',
                     MozUserSelect: 'none',
                     msUserSelect: 'none'
                   }}>
                <span className="opacity-70">"</span>
                {userInput.length > 50 ? `${userInput.substring(0, 50)}...` : userInput}
                <span className="opacity-70">"</span>
              </div>
            )}

            {/* 底部装饰 */}
            <div className="mt-16 flex justify-center">
              <div className="w-32 h-px bg-gradient-to-r from-transparent via-white via-50% to-transparent opacity-30"></div>
            </div>
          </div>
        </div>
      )}

      {/* 历史记录面板 */}
      <div className={`transition-all duration-500 ${hideMainContent ? 'opacity-0 pointer-events-none' : 'opacity-100'}`}>
        <HistoryPanel
          history={history}
          onSelectHistory={handleSelectHistory}
          onHistoryUpdate={handleHistoryUpdate}
          onOpenBackgroundPreview={handleOpenBackgroundPreview}
        />
      </div>
    </div>
  )
}

export default App
